package com.kevin.miniospring;

import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

/**
 * @author Kevin Liu
 * @date 2020/6/10 8:23 上午
 */
public class MinioSpringRegistrar implements ImportBeanDefinitionRegistrar {


    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AnnotationAttributes mapperScanAttrs = AnnotationAttributes
                .fromMap(importingClassMetadata.getAnnotationAttributes(EnableMinioOss.class.getName()));
        if(mapperScanAttrs == null) {
            return;
        }
        String[] values = mapperScanAttrs.getStringArray("value");
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(BucketRegister.class);
        builder.addPropertyValue("buckets",values);
        builder.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
        registry.registerBeanDefinition(generateBaseBeanName(importingClassMetadata,0), builder.getBeanDefinition());

    }
    private static String generateBaseBeanName(AnnotationMetadata importingClassMetadata, int index) {
        return importingClassMetadata.getClassName() + "#" + BucketRegister.class.getSimpleName() + "#" + index;
    }
}
